package controller

import (
	. "api/model"
	"net/http"
	"strconv"
	"github.com/gin-gonic/gin"
)

func CreateCharge(c *gin.Context) {
	cg := Charge{}
	err := c.BindJSON(&cg)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"error": err.Error()})
		return
	}

	err = cg.CreateCharge(cg.Phone, cg.Amount)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"status": 200, "msg": "success"})
}

func GetCharge(c *gin.Context) {
	status := c.Query("status")
	phone := c.Query("phone")

	cg := Charge{}
	if status != "" || phone != "" {
		ret, err := cg.QueryCharge(status, phone)
		if err != nil {
			c.JSON(http.StatusOK, gin.H{"error": err.Error()})
			return
		}
		if ret == nil {
			ret = make([]*Charge, 0)
		}

		c.JSON(http.StatusOK, gin.H{"status": 200, "msg": "success", "data": ret})
	} else {
		ret, err := cg.GetCharge()
		if err != nil {
			c.JSON(http.StatusOK, gin.H{"error": err.Error()})
			return
		}
		if ret == nil {
			ret = make([]*Charge, 0)
		}

		c.JSON(http.StatusOK, gin.H{"status": 200, "msg": "success", "data": ret})
	}
}

func UpdateCharge(c *gin.Context) {
	id, err := strconv.Atoi(c.Query("id"))
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"error": err.Error()})
		return
	}

	cg := Charge{}

	err = c.BindJSON(&cg)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"error": err.Error()})
		return
	}

	status := cg.Status
	if status != 0 && status != 1 && status != 2 && status != -1 {
		c.JSON(http.StatusOK, gin.H{"error": "status值错误"})
		return
	}

	err = cg.UpdateCharge(id, status)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"status": 200, "msg": "success"})
}